#python modules
import logging
import os
import datetime

#web modules
import webapp2
import jinja2

#google modules
from google.appengine.api import users

#application modules
from config import config
from models.models import *

jinja_environment = jinja2.Environment(autoescape=True,loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '../views')))

class GridHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        system_date = datetime.datetime.now().strftime("%d-%m-%Y")

        categoryService = CategoryService()

        categories = categoryService.get_all(user)

        # We are using the template module to output the page.
        template = jinja_environment.get_template('category_grid.html')		
        template_values = {'username':user.nickname(),
                           'url': users.create_logout_url("/"),
                           'system_date':system_date,
                           'categories':categories}
        self.response.out.write(template.render(template_values))

class ValidateHandler(webapp2.RequestHandler):
    def post(self):
        user = users.get_current_user()
        name = self.request.get("name")

        categoryService = CategoryService()
        if categoryService.get_by_name(name,user) == None:
            self.response.out.write("true")
        else:
            logging.info("the category %s already existe" % (name))            
            self.response.out.write("false")
        

class EditHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        system_date = datetime.datetime.now().strftime("%d-%m-%Y")
        
        id_category = int(self.request.GET['id_category'])

        if id_category == -1:
            category = Category()
        else:
            categoryService = CategoryService()
            category = categoryService.get_by_id(id_category,user)

        # We are using the template module to output the page.
        template = jinja_environment.get_template('category_edit.html')		
        template_values = {'username':user.nickname(),
                           'url': users.create_logout_url("/"),
                           'system_date':system_date,
                           'category':category}
        self.response.out.write(template.render(template_values))

    def post(self):
        logging.info("getting user...")
        user = users.get_current_user()
        
        categoryService = CategoryService()

        logging.info("getting action...")
        is_save = self.request.get('btnSave')
        is_cancel = self.request.get('btnCancel')
        is_delete = self.request.get('btnDelete')
        id_category = int(self.request.get('id_category'))

        logging.info("Save: %s, Cancel: %s, Delete: %s, Id_category: %s" % (is_save,is_cancel,is_delete,id_category))
        logging.info(self.request.arguments())

        if is_delete:
            logging.info ("Deleting Category....")            
            c = categoryService.get_by_id(int(id_category),user)
            categoryService.delete(c,user)
        elif is_cancel:
            pass
        else:
            logging.info ("Saving Category....")
            if id_category == -1:
                c = Category()
            else:
                c = categoryService.get_by_id(id_category,user)
                
            c.name = self.request.get('name')
            c.type = self.request.get('type')
            categoryService.save(c,user)

        logging.info ("Returning....")
        self.redirect("/category/grid/")
